package com.yc.baihe.utils;

import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.jsp.PageContext;

import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;

public class UploadUtil {
	
	public static  String PATH=SessionAttributeNames.PATH;
	private static final String ALLOWED="gif,jpg,png,jpeg";//可以上传的文件扩展名
	private static final String DENIED="exe,bat,jsp,html";//不允许上传的文件扩展名
	private static final int TOTALMAXSIZE=20*1024*1024;//最多上传的文件大小
	private static final int SINGLEFILESIZE=1024*1024;//最大的单个文件大小
	
	public Map<String,String> update(PageContext context) throws Exception{
		Map<String,String> map=new HashMap<String,String>();
		
		SmartUpload su=new SmartUpload();
		su.initialize(context);//初始化
		
		//参数设置
		su.setAllowedFilesList(ALLOWED);
		su.setDeniedFilesList(DENIED);
		su.setTotalMaxFileSize(TOTALMAXSIZE);
		su.setMaxFileSize(SINGLEFILESIZE);
		su.setCharset("utf-8");
		
		su.upload();//开始上传
		
		Request request=su.getRequest();
		@SuppressWarnings("rawtypes")
		Enumeration enums=request.getParameterNames();
		String str;
		while(enums.hasMoreElements()){
			str=(String) enums.nextElement();
			map.put(str, request.getParameter(str));
		}
		
		//说明里面有文件
		Files fs=su.getFiles();
		if(fs!=null && fs.getCount()>0){//如果上传没有丢失文件
			@SuppressWarnings("unchecked")
			Collection<File> files=fs.getCollection();
			String fileName;
			String path="";
			for(File fl:files){
				if(!fl.isMissing()){
					fileName=PATH+"/"+new Date().getTime()+""+new Random().nextInt(1000)+"."+fl.getFileExt();
					
					System.out.println(fileName);
					//保存
					fl.saveAs(fileName,SmartUpload.SAVE_VIRTUAL);
					path+=fileName+"-";
				}
			}
			
			if("".equals(path)){
				map.put("photo", "");
			}else{
				map.put("photo", path.substring(0,path.lastIndexOf("-")));
			}
		}
		return map;
	}

}